﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using GameView.Comment;
using GameView.Models;
using GameView.Services;
using GameView.Services.Comment;
using GameView.Services.Dtos;
using GameView.Services.Dtos.Persons;
using GameView.Views;
using MaterialDesignThemes.Wpf;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;

namespace GameView.ViewModels
{
    public partial class UserAddNewViewModel : ObservableValidator
    {
        private readonly UserService _service;
        private readonly RoleService _roleService;

        public UserAddNewViewModel(UserService service, RoleService roleService)
        {
            _service = service;
            _roleService = roleService;
            LoadPG().ConfigureAwait(false);
        }

        private async Task<bool> LoadPG()
        {
            var rolse = await _roleService.GetAllAsync();
            foreach (var r in rolse.Data)
            {
                RoleOptions.Add(r);
            }
            SelectedRole = RoleOptions[0];
            if (_persong != null)
            {
                Id = _persong.Id;
                Name = _persong.Name;
                PhoneNumber = _persong.PhoneNumber;
                Account = _persong.Account;
                //=personnel.RoleId.Value;
                Tile = "修改用户信息";
                var now = RoleOptions.FirstOrDefault(q => q.Id == _persong.RoleId.Value);
                SelectedRole = now;
            }
            return true;
        }

        [ObservableProperty]
        private bool _isLoading = false;

        [ObservableProperty]
        private ObservableCollection<RoleOutDto> _roleOptions = [];

        [Required(ErrorMessage = "角色不能为空")]
        public int NowRoleId => SelectedRole?.Id ?? 0;

        [ObservableProperty]
        private string _tile = "添加用户";

        [ObservableProperty]
        private int _id = 0;

        [ObservableProperty]
        [Required(ErrorMessage = "角色不能为空")]
        [NotifyCanExecuteChangedFor(nameof(SubmitCommand))]
        [NotifyPropertyChangedFor(nameof(NowRoleId))] // 当SelectedRole变化时通知NowRoleId
        private RoleOutDto? _selectedRole;

        [ObservableProperty]
        [NotifyDataErrorInfo]
        [NotifyCanExecuteChangedFor(nameof(SubmitCommand))]
        [Required(ErrorMessage = "用户名称不能为空")]
        private string _account = string.Empty;

        [ObservableProperty]
        private string _name = string.Empty;

        [ObservableProperty]
        private string _phoneNumber = string.Empty;

        private PersonnelOutDto _persong;

        public void SetEdit(PersonnelOutDto personnel)
        {
            if (personnel == null)
                return;
            IsEditAndMer = false;
            _persong = personnel;
            if (_persong.RoleId == 3)
            {
                IsEditAndMer = true;
                _ = LoadChildrensFromApi(_persong.Id);
            }
        }

        [RelayCommand(CanExecute = nameof(CanSubmit))]
        private async Task Submit()
        {
            bool isOK = false;
            object msg = null;
            if (Id <= 0)
            {
                var dto = new PersonnelAddDto
                {
                    Name = Name,
                    Account = Account,
                    RoleId = NowRoleId,
                    PhoneNumber = PhoneNumber
                };
                var res = await _service.AddNew(dto);
                isOK = res.StatusCode == 200;
                msg = res.Errors;
            }
            else
            {
                var dto = new PersonnelUpdateDto
                {
                    Id = Id,
                    Name = Name,
                    Account = Account,
                    RoleId = NowRoleId,
                    PhoneNumber = PhoneNumber
                };
                var res = await _service.Update(dto);
                isOK = res.StatusCode == 200;
                msg = res.Errors;
            }
            if (isOK)
            {
                // 关闭弹窗
                DialogHost.CloseDialogCommand.Execute(null, null);
                GlobalMessage.Instance.ShowSuccess("操作成功！");
            }
            else
            {
                GlobalMessage.Instance.ShowError(JSON.Serialize(msg));
            }
        }

        private bool CanSubmit() => !HasErrors && NowRoleId > 0 && !Account.IsNullOrEmpty();

        #region 关于子账户

        [ObservableProperty]
        private bool _isEditAndMer = false;

        [ObservableProperty]
        private ObservableCollection<PersonnelSimple> _childrens = [];

        [ObservableProperty]
        [NotifyCanExecuteChangedFor(nameof(SubmitChildrenCommand))]
        private string _accountChildren = string.Empty;

        [ObservableProperty]
        private PersonnelSimple _selectedChildren = null;

        [RelayCommand(CanExecute = nameof(CanSubmitChildren))]
        private async Task SubmitChildren()
        {
            var dto = new PersonnelAddDto
            {
                ParentId = _persong.Id,
                Name = Account,
                Account = AccountChildren,
                RoleId = NowRoleId,
                PhoneNumber = PhoneNumber
            };
            var res = await _service.AddNew(dto);
            if (res.StatusCode == 200)
                await LoadChildrensFromApi(_persong.Id);
        }

        private bool CanSubmitChildren() => !AccountChildren.IsNullOrEmpty();

        [RelayCommand]
        private async Task DeleteAsync(PersonnelSimple personnel)
        {
            IsLoading = true;
            await Task.Delay(200);
            try
            {
                var view = new MsgViewDialogView("警告", 3002, "您确认要删除用户", personnel.Account, "的数据吗？");
                view.SetPP("UserDialog");
                var resxx = await ExtentHelper.GetService<IDialogService>().ShowDialog(view, "UserDialog");
                if (!(bool)resxx)
                    return;
                var res = await _service.Delete([personnel.Id]);
                if (res.StatusCode != 200)
                {
                    GlobalMessage.Instance.ShowError(JSON.Serialize(res.Errors));
                    return;
                }
                GlobalMessage.Instance.ShowSuccess($"数据删除成功！");
                await LoadChildrensFromApi(_persong.Id);
            }
            catch (Exception ex)
            {
                GlobalMessage.Instance.ShowError($"数据加载错误：{ex.Message}");
            }
            finally
            { IsLoading = false; }
        }

        [RelayCommand]
        private async Task PasswordResetAsync(PersonnelSimple personnel)
        {
            IsLoading = true;
            await Task.Delay(200);
            try
            {
                var view = new MsgViewDialogView("提示", 3004, "您确认要重置用户", personnel.Account, "的密码吗？");
                view.SetPP("UserDialog");
                var xx = await ExtentHelper.GetService<IDialogService>().ShowDialog(view, "UserDialog");
                if (!(bool)xx)
                    return;
                var res = await _service.ResetPassword(personnel.Id);
                if (res.StatusCode != 200)
                {
                    GlobalMessage.Instance.ShowError(JSON.Serialize(res.Errors));
                    return;
                }
                else if (res.StatusCode == 200 && !res.Data.IsNullOrEmpty())
                {
                    view = new MsgViewDialogView("提示", 3001, "用户：", personnel.Account, "新的密码为：", res.Data, ",请妥善保存您的新密码！");
                    view.SetHasCancel(false);
                    view.SetPP("UserDialog");
                    await ExtentHelper.GetService<IDialogService>().ShowDialog(view, "UserDialog");
                }
            }
            catch (Exception ex)
            {
                GlobalMessage.Instance.ShowError($"数据加载错误：{ex.Message}");
            }
            finally
            { IsLoading = false; }
        }

        private async Task LoadChildrensFromApi(int pid)
        {
            Childrens.Clear();
            var p = await _service.GetChildrensAsync(pid);
            if (p == null || p.Data.IsNullOrEmpty())
                return;
            foreach (var child in p.Data)
            {
                Childrens.Add(child);
            }
        }

        #endregion 关于子账户
    }
}